//
//  PictureView.swift
//  01MicroBlog
//
//  Created by Apple on 15/8/3.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit
import SDWebImage

let WJStatusPictureViewSelectPictureNotificationName = "StatusPictureViewDidSelectPictureNotification"
let StatusPictureViewSelectPictureURLsKey = "StatusPictureViewDidSelectPictureURLs"
let StatusPictureViewSelectPictureIndexPathKey = "StatusPictureViewDidSelectPictureIndexPath"
let StatusPictureViewSelectPicturePositionKey = "StatusPictureViewSelectPicturePositionKey"

var picturePosition:CGRect?

/// MARK: - StatusPictureView
class StatusPictureView: UICollectionView {

    var status:Status? {
        didSet{
            sizeToFit()
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    /// 计算视图大小
    private func calcViewSize() -> CGSize {
        // 0. 准备常量
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        // 每一行最多显示的图片数量
        let rowCount = 3
        
        pictureLayout.itemSize = itemSize
        
        // 1. 根据图片数量计算视图大小
        let count = status?.pictureURLs?.count ?? 0
        
        // 1》 没有图片
        if count == 0 {
            return CGSizeZero
        }
        
        // 2> 1张图片
        if count == 1 {
            
          let key:String = status!.pictureURLs![0].absoluteString
          let iconCache = SDWebImageManager.sharedManager().imageCache
          let image = iconCache.imageFromDiskCacheForKey(key)
            
          var size = CGSize(width: 150, height: 120)
            
            // 下载图片失败，用默认的图片大小
            if image != nil {
                size = image.size
            }
            
            // 判断图片尺寸是否比较极端
            size.width = size.width > UIScreen.mainScreen().bounds.size.width ? CGFloat(150) : image.size.width
            size.width = size.width < 40 ? CGFloat(40) : image.size.width
            
            pictureLayout.itemSize = size
            return size
        }
        
        // 3> 4张图片 2 * 2
        if count == 4 {
            let w = itemSize.width * 2 + margin
            
            return CGSize(width: w, height: w)
        }
        
        // 4> 其他
        /**
        2, 3
        5, 6
        7, 8, 9
        */
        // 计算行数
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + margin * CGFloat(rowCount - 1)
        let h = itemSize.height * CGFloat(row) + margin * CGFloat(row - 1)
        
        return CGSize(width: w, height: h)
    }

    
    private let pictureLayout = UICollectionViewFlowLayout()
    private let reuseId = "pictureView_cell"
    
   override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: pictureLayout)
    
        backgroundColor = UIColor.grayColor()
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: reuseId)
        self.dataSource = self
        self.delegate = self
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    
}



// 在swift中，协议同样可以用extension来写。可以定义一组协议，放在一起，以便维护和阅读
// MARK: - StatusPictureView代理协议
extension StatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 图片的初始位置
//        let rect = cellScreenFrame(indexPath)
        // 图片最终位置
//        let desRec = cellFullScreenFrame(indexPath)
        
        // 测试点击的图片的位置
//        let testView = UIView()
//        
//        testView.backgroundColor = UIColor.redColor()
//        print("testView---\(testView)")
//        UIApplication.sharedApplication().keyWindow?.addSubview(testView)
//        testView.frame = desRec
//        print(testView.frame)
        
        NSNotificationCenter.defaultCenter().postNotificationName(WJStatusPictureViewSelectPictureNotificationName, object: self, userInfo: [StatusPictureViewSelectPictureURLsKey: status!.pictureLargeURLs!, StatusPictureViewSelectPictureIndexPathKey: indexPath])

    }
    
    // 返回图片在屏幕上的原始位置
    func cellScreenFrame(indexPath:NSIndexPath) -> CGRect{
        let cell = cellForItemAtIndexPath(indexPath)!
//        print("cell---\(cell)")
        
        return self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }
    
    // 计算大图在屏幕上的最终位置
    func cellFullScreenFrame(indexPath:NSIndexPath) -> CGRect{
        
        let key = status!.pictureURLs![indexPath.row].absoluteString
        let thumbnailPic = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        let rate = thumbnailPic.size.height / thumbnailPic.size.width
        let screenSize = UIScreen.mainScreen().bounds.size
        
        var y:CGFloat = 0
        let imgH = screenSize.width * rate
        if imgH < screenSize.height {
            y = (screenSize.height - imgH) * 0.5
        }
        return CGRect(x: 0, y: y, width: screenSize.width, height: imgH)
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        // 有status，没有pictureURLs
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseId, forIndexPath: indexPath) as! StatusPictureViewCell
        cell.imageURL = status!.pictureURLs![indexPath.item]
        
        return cell
    }
}

/// MARK: - StatusPictureViewCell
class StatusPictureViewCell: UICollectionViewCell {
    private var imageURL:NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL)
            
            if imageURL?.absoluteString.pathExtension.lowercaseString != "gif" {
                gifImageView.hidden = true
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    private func setUpUI() {
        contentView.addSubview(iconView)
        iconView.addSubview(gifImageView)
        
        iconView.ff_Fill(contentView)
        gifImageView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil)
    }
    
    private lazy var iconView:UIImageView = {
        let iv = UIImageView()
        
//        iv.contentMode
        
        // 设置图片框的内容模式为，等比例缩放，居中填充，多余的部分切掉
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }()
    
     private lazy var gifImageView:UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}



